<?php

namespace backend\controllers;

use common\business\CommonHelper;
use common\business\EhrHelper;
use common\business\employee\EmployeeApiHandler;
use common\business\task\TaskService;
use common\consts\CommonResources;
use common\consts\Consts;
use common\helpers\DateHelper;
use common\helpers\ExcelHelper;
use common\helpers\StringUtil;
use common\models\Department;
use common\models\EmployeePhoto;
use common\models\Task;
use common\result\ActionResult;
use Yii;
use common\models\Employee;
use common\models\EmployeeSearch;
use yii\db\ActiveQuery;
use yii\db\Exception;
use yii\helpers\Json;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * EmployeeController implements the CRUD actions for Employee model.
 */
class EmployeeController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Employee models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new EmployeeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Employee model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Employee model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Employee();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Employee model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Employee model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Employee model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Employee the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Employee::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSyncEmployeeDepartmentRelation($department_id = null){
        $departmentInDb = Department::findOne($department_id);
        $requestData = ['department_number' => $departmentInDb->number];
        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE_DEPARTMENT, 'hr', Consts::NO, Json::encode($requestData));
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }

    public function actionSyncToQywx(){
        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE_TO_QYWX, 'qywx');
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }

    public function actionSyncFromHr($department_id = null){
        $requestDataStr = '';
        if (!StringUtil::isNullOrWhiteSpace($department_id)){
            $departmentInDb = Department::findOne($department_id);
            $requestData = ['department_number' => $departmentInDb->number];
            $requestDataStr = Json::encode($requestData);
        }

        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE, 'hr', Consts::NO, $requestDataStr);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }

    public function actionImport(){
        return $this->render('import', [

        ]);
    }

    public function actionExportToCsv(){
        set_time_limit(0);
        $searchModel = new EmployeeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $fileName = Yii::t('app', 'Employees').DateHelper::todayDate(false).'.csv';
        $format = $this->getExportFormat();
        ExcelHelper::exportToCsv($fileName, $dataProvider->query, $format);
    }

    /**
     * @return array
     */
    protected function getExportFormat(){
        $format = [
            [
                'label' => Yii::t('app', 'Name'),
                'value' => 'employee_name',
            ],
            [
                'label' => Yii::t('app', 'Employee Number'),
                'value' => 'employee_number',
            ],
            [
                'label' => Yii::t('app', 'Gender'),
                'value' => function ($model) {
                    return EhrHelper::getGenderByIntValue($model['employee_gender']);
                },
            ],
            [
                'label' => Yii::t('app', 'Birthday'),
                'value' => 'employee_birthday',
            ],
            [
                'label' => Yii::t('app', 'Email'),
                'value' => 'employee_email',
            ],
            [
                'label' => Yii::t('app', 'Mobile'),
                'value' => 'employee_mobile',
            ],
            //防止身份证号显示为科学计数法
            [
                'label' => Yii::t('app', 'Id Card No'),
                'value' => function ($model) {
                    return sprintf("%s\t", $model['employee_id_card_num']);
                },
            ],
            [
                'label' => Yii::t('app', 'Native Place'),
                'value' => 'employee_native_place',
            ],
            [
                'label' => Yii::t('app', 'Blood Type'),
                'value' => 'employee_blood_type',
            ],
            [
                'label' => Yii::t('app', 'Wed Status'),
                'value' => 'employee_wed_status',
            ],
            [
                'label' => Yii::t('app', 'Nationality'),
                'value' => 'employee_nationality',
            ],
            [
                'label' => Yii::t('app', 'Folk'),
                'value' => 'employee_folk',
            ],
            [
                'label' => Yii::t('app', 'Hklx'),
                'value' => 'employee_hklx',
            ],
            [
                'label' => Yii::t('app', 'HR Id'),
                'value' => 'employee_hr_id',
            ],
            [
                'label' => Yii::t('app', 'HR Status'),
                'value' => 'employee_hr_status',
            ],
            [
                'label' => Yii::t('app', 'Mdm Status'),
                'value' => 'employee_mdm_status',
            ],
        ];
        return $format;
    }

    public function actionGetPhoto($number){
        $employeePhoto = EmployeePhoto::findOne(['employee_number' => $number]);
        $content = EhrHelper::getEmployeePhoto($employeePhoto);
        $returnVal = sprintf('<image src="%s" alt="%s_%s" />', $content, $employeePhoto->employee_number, $employeePhoto->employee_name);
        echo $returnVal;
    }

    public function actionSyncPhoto($department_id = null){
        $requestDataStr = '';
        if (!StringUtil::isNullOrWhiteSpace($department_id)){
            $departmentInDb = Department::findOne($department_id);
            $requestData = ['department_number' => $departmentInDb->number];
            $requestDataStr = Json::encode($requestData);
        }

        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE_PHOTO, 'hr', Consts::NO, $requestDataStr);
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }

    /**
     * @param $ids4Delete string
     * @return string
     */
    public function actionBatchDelete(){
        $params = Yii::$app->request->post();
        $idsArr = explode(',', $params['ids4Delete']);

        $idListArr = [];
        foreach ($idsArr as $id){
            $objInDb = Employee::findOne([
                'id' => $id,
            ]);
            array_push($idListArr, $objInDb->id);
        }

        $result = (new EmployeeApiHandler())->batchDeleteEmployee($idListArr);
        return $result->toJson();
    }
}
